//用户认证和token解析中间件
const jwt = require("jsonwebtoken");
const fs = require("fs");
const path = require("path");
const { TOKEN_VALID, HAS_NOTAUTHOUPDATE } = require("../app/constants");
const publickey = fs.readFileSync(path.resolve(__dirname, "../app/public.key"));
const database = require("../app/database");

//判断token是否有效
const authorverify = async (ctx, next) => {
  //如果没有token
  if (!ctx.headers.authorization) {
    return ctx.app.emit("error", new Error(TOKEN_VALID), ctx);
  }
  try {
    let token = ctx.headers.authorization.replace("Bearer ", "");
    const user = jwt.verify(token, publickey, {
      algorithms: ["RS256"],
    });
    ctx.user = user;
    await next();
  } catch (e) {
    return ctx.app.emit("error", new Error(TOKEN_VALID), ctx);
  }
};

//修改资源时的权限认证
const permissionverify = async (ctx, next) => {
  const paramskey = Object.keys(ctx.params)[0];
  //抽离出table名
  const tablename = paramskey.replace("id", "");

  //抽离出id
  const keyid = ctx.params[paramskey];
  const { id } = ctx.user;
  const str = `
    select * from ${tablename} where id=? and user_id=?
  `;
  const [result] = await database.execute(str, [keyid, id]);
  if (result.length <= 0) {
    return ctx.app.emit("error", new Error(HAS_NOTAUTHOUPDATE), ctx);
  }

  await next();
};

module.exports = {
  authorverify,
  permissionverify,
};
